/* eslint-disable import/extensions */
/* eslint-disable no-plusplus */

import ElEditable from '@components/el-editable';
import {
  orderCommonSubmitOrder,
  orderCommonSaveOrder,
  queryOrderInfo,
  orderProductList,
  getOrderAddressList
} from '@api/m_mall_web_v1.js';
import { isObject, throttle } from 'lodash';
import * as CONSTS from './index.const';
import { IndexService } from './index.service';
import { SupplierAndContractComponent } from '~/components/purchase-order/supplier-and-contract';
import { CarrywayAndAddressComponent } from '~/components/purchase-order/carryway-and-address';
import { PurchaseProductsListComponent } from '~/components/purchase-order/purchase-products-list';

const indexService = new IndexService();
export default {
  components: {
    ElEditable,
    SupplierAndContractComponent,
    CarrywayAndAddressComponent,
    PurchaseProductsListComponent
  },
  inject: ['apiMMallWeb', 'reload'],
  data() {
    return {
      ...CONSTS,
      active_index: 1,
      step_count: 1, // 仅用于记录是否是第一次进入第三步
      dialogVisible: false,
      submit_loading: false,
      bus_model: '2',
      is_edit: false,
      productLoading: false,
      disabled: false,
      extend_model: [], // 传给form-render所需要的经过整理的内容
      base_extend_data: [], // 从接口拿到的原始的表单配置数据，提交的时候需要
      form_data: {
        active_index: this.active_index,
        // id: '',
        // detail_id: '',
        supplier: '',
        contract: '',
        carryway: '',
        address: '',
        address_all: [], // 编辑时要用
        ordertype: '',
        onsignOrderType: '2',
        payway: '',
        address_full: {},
        // operation: '',
        remark: '',
        extend: {},
        products: []
      },
      submit_data: {
        busModel: '',
        busFunction: '1',
        orderType: '', // 这个不要了，但是前端还要传空
        orderTypeId: '', // 订单类型
        payType: '', // 支付方式
        payUse: '', // 支付用途
        transportType: '', // 承运方式
        remark: '', // 备注
        orderCode: '', // 订单编码
        orderDetailId: '', // 订单详情id
        orderId: '', // 订单id
        // 第一步供应商
        supplierVo: {
          vendorCode: '',
          vendorName: ''
        },
        contractVo: null, // 第一步-合同
        saveProductVO: null, // 第二步产品
        addressResDto: null, // 第三步-地址
        orderAppendPOS: null // 第三步-附加信息
      },
      readonly_formdata: {
        supplier: '',
        contract: ''
      },
      storageAddress: {},
      thirdExpandVerifyFlag: false, // 把第三步的校验提出来
      isFirstMount: true
    };
  },
  watch: {
    active_index: {
      handler() {
        document.querySelector('.nuxt-main').scrollTop = 0;
      }
    }
  },
  computed: {
    queryParams() {
      return {
        orderId: this.$route.query.id,
        reAdd: this.$route.query.reAdd
      };
    }
  },
  mounted() {
    this.initGlobalBtn();
  },
  beforeRouteUpdate(to, from, next) {
    next();
    this.reload();
  },
  created() {
    this.getFullAddress();
    this.businessModel = '';
  },
  methods: {
    getFullAddress() {
      this.$axios.$post(getOrderAddressList).then(res => {
        this.form_data.address_all = res.payload || [];
        this.getInitialization();
      });
    },
    getInitialization() {
      // 编辑模式
      if (this.queryParams.orderId) {
        if (this.queryParams.reAdd) {
          this.active_index = 2;
        }
        this.disabled = true;
        this.productLoading = true;
        this.$axios({
          url: queryOrderInfo,
          method: 'post',
          data: {
            orderId: this.queryParams.orderId
          }
        }).then(res => {
          const result = res.data.payload ? res.data.payload : {};
          result.transportType = result.transportType
            ? `${result.transportType}`
            : result.transportType;
          // 其实这里直接把结果赋值给submit_data就可以了，但是为了某些更改项的对应，还是重新一一赋值一下。
          this.resetDetailInfo(result);
          this.showCarrywayAndAddress = true;
          this.is_edit = true;
        });
      } else {
        this.showCarrywayAndAddress = true;
      }
    },
    // 额外单独获取产品详情
    getProductsList(id) {
      this.$axios({
        url: orderProductList,
        method: 'post',
        data: {
          orderDetailId: id,
          page: 1,
          pageSize: 9999
        }
      })
        .then(res => {
          const result = res.data.payload.content.length
            ? res.data.payload.content
            : [];
          // 毫无意义的数据转换，为后端各接口返回值不匹配买单
          result.forEach(item => {
            const newItem = item;
            newItem.attribute1 = newItem.specs;
            newItem.productName = newItem.productNameCN;
            newItem.attribute5 = newItem.barCode;
          });
          this.submit_data.saveProductVO = result;
          this.form_data.products = result;
        })
        .finally(() => {
          this.productLoading = false;
          this.disabled = false;
        });
    },
    resetDetailInfo(detail) {
      // 最先调用第三步的附加信息，获取其表单框架
      // 先给第二步的详情赋值,其实就是从结果里单独抽出来
      let judgeAddress = null;
      if (this.form_data.address_all.length > 0) {
        judgeAddress = this.form_data.address_all.find(
          item => item.id === detail.addressResDto.id
        );
      } else {
        judgeAddress = undefined;
      }
      const readOnlyDetail = {
        vendorName: detail.supplierVo.vendorName,
        contract: detail.contractVo.supplierName
      };
      this.readonly_formdata = indexService.mappingOrderDetailReadonly(
        readOnlyDetail
      );
      // 然后给submit_data赋值，多说一下，submit_data是最后提交的经过整理的内容，而form_data是未经整理的散乱的。
      // 换句话说，submit_data是给后端接口用的，form_data是给前端自己用的。
      this.submit_data = {
        createType: detail.createType || '',
        busModel: detail.busModel,
        busFunction: '1',
        orderType: '', // 订单类型
        orderTypeId: detail.orderTypeId,
        payType: detail.payType, // 支付方式
        payUse: detail.payUse, // 支付用途
        transportType: detail.transportType || '', // 承运方式
        remark: detail.remark, // 备注
        orderCode: detail.orderCode, // 订单编码
        orderDetailId: detail.orderDetailId, // 订单详情id
        orderId: this.queryParams.reAdd ? '' : detail.orderId, // 订单id
        // 第一步供应商
        supplierVo: detail.supplierVo,
        contractVo: detail.contractVo, // 第一步-合同
        addressResDto: judgeAddress !== undefined ? detail.addressResDto : {}, // 第三步-地址
        orderAppendPOS: detail.orderAppendPOS // 第三步-附加信息
      };
      // 还要给前端数据form_data赋值
      this.form_data = {
        products: [],
        active_index: this.active_index,
        detail_id: this.submit_data.orderDetailId,
        supplier: this.submit_data.supplierVo.vendorCode,
        contract: `${this.submit_data.contractVo.supplierCode || ''}${this
          .submit_data.contractVo.productLineCode || ''}${this.submit_data
          .contractVo.businessModelCode || ''}${this.submit_data.contractVo
          .marketCode || ''}`,
        carryway: this.submit_data.transportType || '',
        address: this.submit_data.addressResDto.userAddressId || '',
        ordertype: this.submit_data.orderTypeId,
        onsignOrderType: '2',
        payway: this.submit_data.payType,
        address_full: this.submit_data.addressResDto,
        remark: this.submit_data.remark
      };
      const obj = {};
      this.submit_data.orderAppendPOS.forEach(item => {
        obj[item.attributeNameValue] = item.attributeValue;
      });
      this.form_data.extend = obj;
      this.businessModel = detail.contractVo.businessModel;
      // 额外获取第二步的产品数据，orderDetailId不从路由拿去，只从这个详情数据中取。
      // 路由实际参数只有orderId是有用的
      this.getProductsList(this.form_data.detail_id);
    },
    initGlobalBtn() {
      const btnObj = {
        type: 'btn',
        arr: []
      };
      const saveDraftBtn = {
        val: '暂存',
        handle: this.onSaveDraft
      };
      const prevBtn = {
        type: 'primary',
        val: '上一步',
        handle: this.onPrev
      };
      const nextBtn = {
        type: 'primary',
        val: '下一步',
        handle: this.onNext
      };
      const submitBtn = {
        type: 'primary',
        val: '提交',
        handle: this.showConfirmDialog
      };
      // if (this.active_index !== 1) {
      //   btnObj.arr.push(prevBtn);
      // }
      if (
        (!this.queryParams.reAdd && this.active_index !== 1) ||
        (this.queryParams.reAdd && this.active_index === 3)
      ) {
        btnObj.arr.push(prevBtn);
      }
      if (this.active_index !== 3) {
        btnObj.arr.push(nextBtn);
      } else {
        btnObj.arr.push(submitBtn);
      }
      btnObj.arr.push(saveDraftBtn);
      this.$store.commit('changeLayoutHandle', btnObj);
    },
    showConfirmDialog() {
      const verifyResult = indexService.verifyStep(3, this.form_data);
      if (verifyResult.pass === true) {
        this.$refs.expandFormRenderer.validate(valid => {
          if (valid) {
            this.dialogVisible = true;
            this.saveTheData();
          } else {
            this.$message({
              message: '您所填写的附加信息有误，请确认后重新填写填',
              type: 'warning'
            });
          }
        });
      } else {
        this.$notify({
          title: '必填项',
          message: verifyResult.message,
          type: 'warning'
        });
      }
    },
    onSubmit: throttle(
      function() {
        if (this.submit_data.transportType === '1') {
          this.submit_data.addressResDto = {};
        } else {
          this.submit_data.addressResDto = this.storageAddress;
        }
        this.submit_loading = true;
        this.$axios({
          url: orderCommonSubmitOrder,
          method: 'post',
          data: this.splitSubmitDataBySteps()
        })
          .then(res => {
            if (res.data.code === '0') {
              this.$router.push('/purchase-order/consign/list');
              this.$message({
                message: '订单提交成功',
                type: 'success'
              });
            }
          })
          .catch(err => {
            if (err.data.code === '200001') {
              this.$router.push('/purchase-order/consign/list');
            }
          })
          .finally(() => {
            this.dialogVisible = false;
            this.submit_loading = false;
          });
      },
      3000,
      {
        leading: true,
        trailing: false
      }
    ),
    async onNext() {
      this.step_count++;
      const verifyResult = indexService.verifyStep(
        this.active_index,
        this.form_data
      );
      if (verifyResult.pass === true) {
        if (this.active_index++ >= 3) this.active_index = 3;
        this.setExpandData();
      } else {
        this.$notify({
          type: 'warning',
          title: '请注意',
          message: verifyResult.message
        });
      }
      this.initGlobalBtn();
    },
    onPrev() {
      this.step_count++;
      if (this.active_index-- <= 1) this.active_index = 1;
      this.initGlobalBtn();
    },
    onSupplierAndContractChange(val, businessModel) {
      // eslint-disable-next-line no-unused-expressions
      businessModel && (this.businessModel = businessModel);
      this.readonly_formdata = indexService.mappingOrderDetailReadonly(val);
      this.submit_data.supplierVo = Object.assign(
        this.submit_data.supplierVo || {},
        val.suppliy
      );
      this.submit_data.contractVo = Object.assign(
        this.submit_data.contractVo || {},
        val.contract
      );
      this.submit_data.busModel = this.submit_data.contractVo.businessModelCode;
      // 这里要清空一些特殊的数据
      // 第2步的产品列表和第三步的订单类型
      if (!this.isFirstMount) {
        if (this.form_data.products.length) {
          this.submit_data.saveProductVO = null;
          this.form_data.products = [];
        }

        if (this.form_data.ordertype) {
          this.form_data.ordertype = '';
          if (this.submit_data.orderTypeId) this.submit_data.orderTypeId = '';
        }
      }
    },
    onAddressChanged(val) {
      // 地址需要全量数据
      this.form_data.address_full = val;
      this.submit_data.addressResDto = Object.assign(
        this.submit_data.addressResDto || {},
        val
      );
      this.storageAddress = this.submit_data.addressResDto;
    },
    saveTheData() {
      // 通过sync和update更新products数据，所以这里要赋值以下，该操作意图等同于onSupplierAndContractChange方法。
      // 赋值第二步选择产品部分数据
      this.submit_data.saveProductVO = this.form_data.products;
      // 复制第三步的三个选项部分（订单类型，承运方式，支付方式，以及备注）
      if (!this.queryParams.reAdd) {
        this.submit_data.orderTypeId = this.form_data.ordertype; // 订单类型
      }
      this.submit_data.orderType = '';
      this.submit_data.transportType = this.form_data.carryway; // 承运方式
      this.submit_data.payType = this.form_data.payway; // 支付方式
      this.submit_data.remark = this.form_data.remark; // 备注

      // 这里，要把expand动态生成的表单，组合成后端想要的数据格式，也就是说，要再反向重组一下。
      const extendResult = this.base_extend_data;
      extendResult.forEach(item => {
        const newItem = item;
        newItem.attributeValue =
          this.form_data.extend[item.attributeNameValue] || '';
      });
      this.submit_data.orderAppendPOS = extendResult;
      if (this.submit_data.transportType === '1') {
        this.submit_data.addressResDto = {};
      } else {
        this.submit_data.addressResDto = this.storageAddress;
      }
    },
    splitSubmitDataBySteps() {
      const curStep = this.active_index; // 当前步骤
      // 这里跟submit_data一模一样，下面选择性的赋值
      // eslint-disable-next-line camelcase
      let splitSubmitData = {
        createType: this.submit_data.createType,
        busModel: '',
        busFunction: '1',
        orderType: '', // 订单类型
        orderTypeId: '', // 订单类型
        payType: '', // 支付方式
        payUse: '', // 支付用途
        transportType: '', // 承运方式
        remark: '', // 备注
        orderCode: this.submit_data.orderCode, // 订单编码
        orderDetailId: this.submit_data.orderDetailId, // 订单详情id
        orderId: this.submit_data.orderId, // 订单id
        // 第一步供应商
        supplierVo: {
          vendorCode: '',
          vendorName: ''
        },
        contractVo: null, // 第一步-合同
        saveProductVO: null, // 第二步产品
        addressResDto: null, // 第三步-地址
        orderAppendPOS: null // 第三步-附加信息
      };
      // 第一步
      // eslint-disable-next-line default-case
      switch (curStep) {
        // 第一步，只存第一步的合同和供应商
        case 1:
          splitSubmitData.supplierVo = this.submit_data.supplierVo;
          splitSubmitData.contractVo = this.submit_data.contractVo;
          splitSubmitData.busModel = this.submit_data.busModel;
          break;
        // 除了第一步的，还额外需要产品部分
        case 2:
          splitSubmitData.supplierVo = this.submit_data.supplierVo;
          splitSubmitData.contractVo = this.submit_data.contractVo;
          this.submit_data.saveProductVO.forEach(item => {
            const newItem = item;
            newItem.originalFactoryCode =
              item.productFactoryCode || item.originalFactoryCode;
            newItem.originalFactoryName =
              item.productFactoryName || item.originalFactoryName;
          });
          splitSubmitData.saveProductVO = this.submit_data.saveProductVO;
          splitSubmitData.busModel = this.submit_data.busModel;
          break;
        // 第三步就比较简单了
        case 3:
          this.submit_data.saveProductVO.forEach(item => {
            const newItem = item;
            newItem.originalFactoryCode =
              item.productFactoryCode || item.originalFactoryCode;
            newItem.originalFactoryName =
              item.productFactoryName || item.originalFactoryName;
          });
          splitSubmitData = this.submit_data;
          break;
      }
      return splitSubmitData;
    },
    saveProgress: throttle(
      // eslint-disable-next-line func-names
      function() {
        this.saveTheData();
        this.$axios({
          url: orderCommonSaveOrder,
          method: 'post',
          data: this.splitSubmitDataBySteps()
        })
          .then(res => {
            const order = isObject(res.data.payload) ? res.data.payload : {};
            this.submit_data.orderId = order.orderId;
            this.submit_data.orderDetailId = order.orderDetailId;
            this.submit_data.orderCode = order.orderCode;
            this.$message({
              type: 'success',
              message: '暂存成功'
            });
          })
          .catch(() => {
            this.$message({
              type: 'warning',
              message: '暂存失败'
            });
          });
      },
      3000,
      {
        leading: true,
        trailing: false
      }
    ),
    async onSaveDraft() {
      const verifyResult = indexService.verifyStep(
        this.active_index,
        this.form_data
      );
      if (verifyResult.pass === true) {
        // 如果不是第三步，直接暂存，如果到了第三步，那么需要校验表单后并且通过后，再暂存
        if (this.active_index === 3) {
          this.$refs.expandFormRenderer.validate(valid => {
            if (valid) {
              this.saveProgress();
            } else {
              this.$message({
                message: '您所填写的附加信息有误，请确认后重新填写填',
                type: 'warning'
              });
            }
          });
        } else {
          this.saveProgress();
        }
      } else {
        this.$notify({
          type: 'warning',
          title: '请注意',
          message: verifyResult.message
        });
      }
    },
    async setExpandData() {
      // 这里为什么在第三步才能调用，因为要依赖于第一步的数据作为接口获取的入参。
      // 所以无法在创建时就调用该方法
      if (this.active_index === 3) {
        const ddbmMap = {
          长期寄售: 'LCONSIGN_INIT',
          短期寄售: 'SCONSIGN_LENG'
        };
        this.base_extend_data = await this.apiMMallWeb.GetAppendInfoOrderV1ApiPOST(
          {
            query: {
              busModel: this.bus_model,
              ddbm: ddbmMap[this.businessModel],
              productLineCode: this.submit_data.contractVo.productLineCode,
              vendorNum: this.submit_data.contractVo.supplierCode,
              page: 1,
              pageSize: 9999
            }
          }
        );
        this.extend_model = indexService.getFormContent(
          this.base_extend_data,
          this.ATTRIBUTE_TYPE_OPTIONS
        );
        // 获取默认值
        const defaultValue = {};
        this.base_extend_data.forEach(item => {
          defaultValue[item.attributeNameValue] = item.defaultValue;
        });
        // 这块逻辑有点烦，因为所有的情况都汇聚到这了。
        // 首先数据有默认值，详情反显值和编辑值三种情况。
        // 除了第一次进入第三步，且非编辑模式时，使用默认值，其他情况都使用编辑值。
        // 注意：反显值，在反显数据获取时，赋值给编辑值了。
        // 导致该复杂逻辑的原因：1、需求，2、业务揉合。
        let finalValue;
        if (this.step_count === 3 && !this.is_edit) {
          finalValue = defaultValue;
          // 给编辑值附上初始值，仅第三次且非编辑模式时赋值
          // 为了如果没修改内容，下次进来还是初始值
          this.form_data.extend = defaultValue;
        } else {
          finalValue = this.form_data.extend;
        }
        this.$nextTick(() => {
          this.$refs.expandFormRenderer.updateForm(finalValue);
        });
      }
    }
  }
};
